package com.zhiwang.planet.ui

import android.annotation.SuppressLint
import android.graphics.Rect
import android.os.Bundle
import com.google.android.material.bottomsheet.BottomSheetDialog
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import com.alipay.sdk.app.PayTask
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerPayComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.mvp.p.PayPresenter
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.p.VipPresenter
import com.zhiwang.planet.mvp.v.AlipayView
import com.zhiwang.planet.mvp.v.DiamondPayView
import com.zhiwang.planet.mvp.v.UserInfoView
import com.zhiwang.planet.mvp.v.VipView
import com.zhiwang.planet.mvvm.model.entity.User
import com.zhiwang.planet.mvvm.model.entity.VipInfo
import com.zhiwang.planet.mvvm.model.entity.VipItem
import com.zhiwang.planet.mvvm.model.entity.VipModel
import com.zhiwang.planet.sdkmodel.alipay.PayResult
import com.zhiwang.planet.ui.adapter.VipChooseAdapter
import com.zhiwang.planet.ui.adapter.VipPrivilegeAdapter
import com.zhiwang.planet.ui.my.VipRecordActivity
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.SimpleDialogBuilder
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_membership.*
import org.json.JSONObject
import javax.inject.Inject

/**
 * vip 开通页面
 */
class MembershipActivity : BaseActivity(), View.OnClickListener, AlipayView, UserInfoView, VipView, DiamondPayView {

    override fun onDiamondPay() {
        //开通之后再次请求vip数据，刷新用户vip信息
        vipPresenter.getVipInfo()
        bottomSheetDialog.dismiss()

        SimpleDialogBuilder()
                .title("开通Vip")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .content("Vip开通成功")
                .build(this@MembershipActivity)
                .show()
    }

    @Inject
    lateinit var payPresenter: PayPresenter

    @Inject
    lateinit var vipPresenter: VipPresenter

    @Inject
    lateinit var userPresenter: UserPresenter

    lateinit var wxApi: IWXAPI

    var vipType = "9"
    var tradeNo: String = ""

    var userInfo: User? = null

    var vipAdapter = VipChooseAdapter()
    var vipPrivilegeAdapter = VipPrivilegeAdapter()
    private lateinit var vipModel: VipModel

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerPayComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(this))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        payPresenter.aliPayView = this
        payPresenter.diamondPayView = this
        userPresenter.userInfoView = this
        vipPresenter.vipView = this
        setContentView(R.layout.activity_membership)
        wxApi = WXAPIFactory.createWXAPI(this, Store.APP_ID)
        com.zhiwang.planet.util.Utils.setStatusBar(this, false, false)
        StatusbarUtil.setStatusBarColor(this, R.color.high_end_black)
        setSupportActionBar(toolbar)
        initRecyclerView()
        setUpListener()
        userPresenter.queryUserInfo()
        vipPresenter.getVipInfo()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.membership_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item!!.itemId == R.id.vip_record) {
            quickStartActivity(VipRecordActivity::class.java)
        }
        return super.onOptionsItemSelected(item)
    }

    private var chosenVipItem: VipItem? = null
    private fun initRecyclerView() {
        vipRecyclerView.addItemDecoration(object : androidx.recyclerview.widget.RecyclerView.ItemDecoration() {

            override fun getItemOffsets(outRect: Rect, view: View, parent: androidx.recyclerview.widget.RecyclerView, state: androidx.recyclerview.widget.RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                val position = parent.getChildLayoutPosition(view)
                if (position % 2 == 0) {
                    outRect.set(0, 0, 8.dp, 0)
                } else outRect.set(8.dp, 0, 0, 0)
            }
        })
        vipRecyclerView.itemAnimator!!.changeDuration = 0
        vipRecyclerView.adapter = vipAdapter
        vipAdapter.setVipModels(arrayListOf())
        vipAdapter.itemChosenListener = object : VipChooseAdapter.OnItemChosenListener {

            override fun onItemChosen(index: Int) {
                //切换
                vip_privilege.visibility = View.VISIBLE
                btn_open_vip_.visibility = View.VISIBLE
                vipType = vipModel.vipList[index].vip
                chosenVipItem = vipModel.vipList[index]
                bindVipPrivilege(vipModel.vipList[index])
            }

        }
    }

    private fun setUpListener() {
        btn_open_vip.setOnClickListener(this)
        btn_open_vip_.setOnClickListener(this)
    }

    lateinit var bottomSheetDialog: BottomSheetDialog
    @SuppressLint("SetTextI18n")
    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_open_vip, R.id.btn_open_vip_ -> {
                if (chosenVipItem == null) {
                    Toaster.message("请先选择您要开通的vip")
                    return
                }
                //bottom vip dialog
                bottomSheetDialog = BottomSheetDialog(this)
                bottomSheetDialog.setContentView(R.layout.open_vip_layout)
                bottomSheetDialog.findViewById<TextView>(R.id.payCancel)!!.setOnClickListener {
                    bottomSheetDialog.dismiss()
                }

                bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.setText(userInfo!!.userId)
                bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.background.alpha = 0
                bottomSheetDialog.findViewById<RadioButton>(R.id.wechatpay)!!.visibility = if (isWechatPayEnabled()) View.VISIBLE else View.GONE
                bottomSheetDialog.findViewById<RadioButton>(R.id.alipay)!!.visibility = if (isAlipayEnabled()) View.VISIBLE else View.GONE
                bottomSheetDialog.findViewById<RadioButton>(R.id.diamondpay)!!.visibility = if (isDiamondpayEnabled()) View.VISIBLE else View.GONE
                bottomSheetDialog.findViewById<TextView>(R.id.vipType)!!.text = chosenVipItem!!.vip_txt
                bottomSheetDialog.findViewById<TextView>(R.id.money)!!.text = "¥${chosenVipItem!!.cost}(${chosenVipItem!!.period_days}天)"
                bottomSheetDialog.findViewById<TextView>(R.id.vip_target)!!.setOnClickListener {
                    val tv = it as TextView
                    if (tv.text == "为自己开通>>") {//切换成
                        tv.text = "为好友开通>>"
                        val editText = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!
                        editText.setText(userInfo!!.userId)
                        //隐藏输入框灰色背景
                        editText.background.alpha = 0
                        editText.isEnabled = false
                    } else {
                        tv.text = "为自己开通>>"
                        val editText = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!
                        editText.background.alpha = 255
                        editText.setText("")
                        editText.isEnabled = true
                    }
                }

                bottomSheetDialog.findViewById<TextView>(R.id.payVip)!!.setOnClickListener {
                    val checkedRadioButtonId = bottomSheetDialog.findViewById<RadioGroup>(R.id.pay_group)!!.checkedRadioButtonId
                    when (checkedRadioButtonId) {
                        R.id.alipay -> /*getAlipaySign()*/ {
                            val userid = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.text.toString()
                            if (TextUtils.isEmpty(userid).not())
                                payPresenter.getAlipaySign(userid, vipType, "alipay_app")
                            else Toaster.message("id不能为空")
                        }

                        R.id.wechatpay -> payByWechat()

                        R.id.diamondpay -> {
                            val userid = bottomSheetDialog.findViewById<EditText>(R.id.userId)!!.text.toString()
                            if (TextUtils.isEmpty(userid).not())
                                payByDiamond(userid)
                            else Toaster.message("id不能为空")
                        }
                    }

                }
                bottomSheetDialog.show()
            }

        }
    }

    private fun isWechatPayEnabled(): Boolean {
        return vipModel.payTypes.isNotEmpty() && vipModel.payTypes.any { it.name == "微信" || it.type == "weixin" }
    }

    private fun isAlipayEnabled(): Boolean {
        return vipModel.payTypes.isNotEmpty() && vipModel.payTypes.any { it.name == "支付宝" || it.type == "alipay" }
    }

    private fun isDiamondpayEnabled(): Boolean {
        return vipModel.payTypes.isNotEmpty() && vipModel.payTypes.any { it.name == "趣钻" || it.type == "qubi" }
    }

    private fun payByDiamond(userid: String) {
        payPresenter.payVipByDiamond(userid, vipType, "qubi")
    }


    private fun payByWechat() {
        //获取微信支付需要的参数
        val content = "{\n" +
                "\"retcode\":\"1\",\n" +
                "\"appid\":\"wx835dae6e8ca8fd3c\",\n" +
                "\"partnerid\":\"ffefe\",\n" +
                "\"prepayid\":\"2343434\",\n" +
                "\"noncestr\":\"dfdff\",\n" +
                "\"timestamp\":\"1543547510351\",\n" +
                "\"package\":\"com.zhiwang.planet\",\n" +
                "\"sign\":\"3rj3i2r3i2rnifn3andfn3rn\"\n" +
                "}"
        val json = JSONObject(content)
        if (json.has("retcode")) {
            val req = PayReq()
            req.appId = json.getString("appid")
            req.partnerId = json.getString("partnerid")
            req.prepayId = json.getString("prepayid")
            req.nonceStr = json.getString("noncestr")
            req.timeStamp = json.getString("timestamp")
            req.packageValue = json.getString("package")
            req.sign = json.getString("sign")
            req.extData = "app data" // optional
            Toast.makeText(this@MembershipActivity, "正在拉起微信", Toast.LENGTH_SHORT).show()
            wxApi.sendReq(req)
        }

    }

    private fun payByAli(sign: String) {
        val payTask = PayTask(this)
        Observable
                .create<Map<String, String>> {
                    val result = payTask.payV2(sign, true)
                    runOnUiThread {
                        handlePayResult(result)
                    }
                    it.onComplete()

                }
                .androidSchedule()
                .`as`(androidAutoDispose())
                .subscribe({

                    //handlePayResult(it)

                }, {

                })
    }

    private fun handlePayResult(it: Map<String, String>?) {
        val payResult = PayResult(it)
        val resultInfo = payResult.result// 同步返回需要验证的信息
        val resultStatus = payResult.resultStatus
        bottomSheetDialog.dismiss()
        val msg: String
        if (TextUtils.equals(resultStatus, "9000")) {
            msg = "支付成功"
        } else if (TextUtils.equals(resultStatus, "6001")) {
            msg = "支付取消"
        } else {
            msg = "支付失败$resultStatus"
        }

        SimpleDialogBuilder()
                .title("开通VIP")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .onButtonClick(View.OnClickListener {
                    if (msg == "支付成功")
                        quickStartActivity(VipRecordActivity::class.java)
                })
                .content("$msg")
                .build(this@MembershipActivity)
                .show()
    }


    var requestManager: RequestManager? = null
    override fun onUserInfoLoad(user: User?) {
        if (user != null) {
            userInfo = user
            if (requestManager == null)
                requestManager = Glide.with(this)
            requestManager?.load(user.avatar)?.into(user_avatar)
            user_name.text = user.userName
        }
    }

    override fun onAlipay(it: String) {
        payByAli(it)
//        tradeNo = it.tradeno
    }


    override fun onLoadVipInfo(vipModel: VipModel) {
        this.vipModel = vipModel
        bindUserVip(vipModel.vipInfo)
        if (vipModel.vipList.isNotEmpty())
            bindVipPrivilege(vipModel.vipList[0])
        bindRecyclerChooser(vipModel.vipList)
    }

    private fun bindRecyclerChooser(vipList: List<VipItem>) {
        vipAdapter.setVipModels(vipList)
    }

    @SuppressLint("SetTextI18n")
    private fun bindUserVip(vipInfo: VipInfo) {
        if ((vipInfo.vipLevel != null) && (!vipInfo.vipLevel.equals("0"))) {
            vip_layout.visibility = View.VISIBLE
            //有vip等级
            user_vip_name.text = vipInfo.vipName
            vip_end_time.text = "VIP到期时间：${vipInfo.end_time}"
            Glide.with(this)
                    .load(com.zhiwang.planet.util.Utils.vipIcon(vipInfo.vipLevel))
                    .into(iv_Vip)
        } else {
            vip_layout.visibility = View.GONE
            vip_end_time.text = "开通VIP尊享特权"
        }
    }

    @SuppressLint("SetTextI18n")
    private fun bindVipPrivilege(vipItem: VipItem) {
        shiwan_text.Title.text = "试玩加成\n${vipItem.shiwan}%"
        qudou_text.Title.text = "开通赠送\n${vipItem.open_reward.toInt() / 10000}万趣豆"
        gongzi_text.Title.text = "每日工资\n${vipItem.daily_pay.toInt() / 10000}万趣豆"
        choujiang_text.Title.text = "每日抽奖\n${vipItem.choujiang}次"
        duihuan_text.Title.text = "兑换趣豆送\n${vipItem.exchange_dgold}%"
        service_text.Title.text = "服务周期\n${vipItem.period_days}天"
    }
}
